package com.crane.common.web.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.common.core.utils.StringUtil;
import com.crane.common.framework.utils.DateUtil;
import com.crane.oss.common.bean.request.QuerySchoolTestCycleReq;
import com.crane.oss.common.bean.resp.KeyValueResp;
import com.crane.oss.enums.*;
import com.crane.oss.school.bean.request.QueryClassesInfoReq;
import com.crane.oss.school.bean.request.QueryTeacherCycleReq;
import com.crane.oss.school.bean.resp.AreaResp;
import com.crane.oss.school.bean.resp.ClassesInfoResp;
import com.crane.oss.school.bean.resp.TeacherCycleResp;
import com.crane.oss.school.service.AreaService;
import com.crane.oss.school.service.ClassesInfoService;
import com.crane.oss.school.service.TeacherCycleService;
import com.crane.oss.sports.XunFeiCommonApiService;
import com.crane.oss.sys.bean.resp.PartyBean;
import com.crane.oss.xunfei.req.QueryTestCycleReq;
import com.crane.oss.xunfei.resp.ApiListResponse;
import com.crane.oss.xunfei.resp.TestCycleResp;
import com.crane.oss.sys.service.PartyService;
import com.crane.oss.web.BaseBusinessController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tyh
 */
@Api(value = "EnumController", tags = {"枚举字典"})
@RestController
@RequestMapping("/api/enum")
public class EnumController extends BaseBusinessController {

    @Autowired
    AreaService areaService;

    @Autowired
    PartyService partyService;

    @Resource
    ClassesInfoService classesInfoService;

    @Autowired
    TeacherCycleService teacherCycleService;

    @Autowired
    XunFeiCommonApiService xunFeiCommonApiService;

    @ApiOperation(value = "学段", notes = "获取学段下拉值")
    @GetMapping("/section")
    public MultiResponse section(@RequestParam(required = false) String schoolSystem) {
        List<Map<String, Object>> list = new ArrayList<>();
        if(StringUtil.isEmpty(schoolSystem)){
            for (SectionEnum section : SectionEnum.values()) {
                Map<String, Object> map = new HashMap<>();
                map.put("key", section.getType());
                map.put("name", section.getRemark());
                list.add(map);
            }
        }else{
            List<SectionEnum> result = SchoolSystemEnum.getSectionEnum(SchoolSystemEnum.getSchoolSystemEnum(schoolSystem));
            for (SectionEnum section : result) {
                Map<String, Object> map = new HashMap<>();
                map.put("key", section.getType());
                map.put("name", section.getRemark());
                list.add(map);
            }
        }
        return MultiResponse.ofWithoutTotal(list);
    }

    @ApiOperation(value = "获取学校学制", notes = "获取学校学制")
    @GetMapping("/systemList")
    public MultiResponse getSchoolSystemList() {
        // 查询列表数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (SchoolSystemEnum sectionEnum : SchoolSystemEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("key", sectionEnum.getType());
            map.put("name", sectionEnum.getRemark());
            list.add(map);
        }
        return MultiResponse.ofWithoutTotal(list);
    }


    @ApiOperation(value = "获取机构年级", notes = "获取当前机构年级")
    @PostMapping("/grade")
    public MultiResponse grade(@RequestBody(required = false) String schoolSystem) {
        // 查询列表数据
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtil.isNotEmpty(schoolSystem)) {
            List<SectionEnum> result = SchoolSystemEnum.getSectionEnum(SchoolSystemEnum.getSchoolSystemEnum(schoolSystem));
            for (SectionEnum sectionEnum : result) {
                List<GradeEnum> gradeEnumList = SectionEnum.getGradeEnum(sectionEnum);
                for (GradeEnum gradeEnum : gradeEnumList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("key", gradeEnum.getType());
                    map.put("name", gradeEnum.getRemark());
                    list.add(map);
                }
            }
            return MultiResponse.ofWithoutTotal(list);
        } else {
            for (GradeEnum gradeEnum : GradeEnum.values()) {
                Map<String, Object> map = new HashMap<>();
                map.put("key", gradeEnum.getType());
                map.put("name", gradeEnum.getRemark());
                list.add(map);
            }
            return MultiResponse.ofWithoutTotal(list);
        }
    }


    @ApiOperation(value = "获取机构年级", notes = "获取当前机构年级")
    @PostMapping("/myGrade")
    public MultiResponse myGrade() {
        // 查询列表数据
        List<Map<String, Object>> list = new ArrayList<>();
        PartyBean partyBean=partyService.queryParty(getPartyId());
        if(null == partyBean || null == partyBean.getSchoolSystem()){
            return MultiResponse.ofWithoutTotal(list);
        }
        List<SectionEnum> result = SchoolSystemEnum.getSectionEnum(Objects.requireNonNull(SchoolSystemEnum.getSchoolSystemEnum(partyBean.getSchoolSystem().toString())));
        for (SectionEnum sectionEnum : result) {
            List<GradeEnum> gradeEnumList = SectionEnum.getGradeEnum(sectionEnum);
            for (GradeEnum gradeEnum : gradeEnumList) {
                Map<String, Object> map = new HashMap<>();
                map.put("key", gradeEnum.getType());
                map.put("name", gradeEnum.getRemark());
                list.add(map);
            }
        }
        return MultiResponse.ofWithoutTotal(list);

    }

    @ApiOperation(value = "管理端获取校区", notes = "获取校区下拉值")
    @GetMapping("/schoolArea")
    public MultiResponse schoolArea() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<AreaResp> schoolAreaList = this.areaService.queryAreaList(getPartyId());

        for (AreaResp schoolArea : schoolAreaList) {
            Map<String, Object> map = new HashMap<>();
            map.put("key", schoolArea.getSchoolId());
            map.put("name", schoolArea.getAreaName());
            list.add(map);
        }

        return MultiResponse.ofWithoutTotal(list);
    }

    @ApiOperation(value = "班级类型", notes = "获取班级类型下拉值")
    @GetMapping("/classesType")
    public MultiResponse classesType() {
        List<Map<String, Object>> list = new ArrayList<>();

        for (ClassesTypeEnum classesType : ClassesTypeEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("key", classesType.getType());
            map.put("name", classesType.getRemark());
            list.add(map);
        }

        return MultiResponse.ofWithoutTotal(list);
    }

    @ApiOperation(value = "班级状态", notes = "获取班级状态下拉值")
    @GetMapping("/classesStatus")
    public MultiResponse classesStatus() {
        List<Map<String, Object>> list = new ArrayList<>();

        for (ClassesStatusEnum classesType : ClassesStatusEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("key", classesType.getType());
            map.put("name", classesType.getRemark());
            list.add(map);
        }

        return MultiResponse.ofWithoutTotal(list);
    }

    @ApiOperation(value = "入学年份", notes = "获取入学年份下拉值")
    @GetMapping("/joinIn")
    public MultiResponse joinIn() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<String> list = new ArrayList<String>();
        for (int i = -11; i < 1; i++) {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, i);
            list.add(DateUtil.formateDate2Str(c.getTime(), "yyyy"));
        }

        for (String v : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("key", v);
            map.put("name", v);
            mapList.add(map);
        }

        return MultiResponse.ofWithoutTotal(mapList);
    }

    @ApiOperation(value = "获取教学周期", notes = "获取教学周期")
    @PostMapping("/teachCycle")
    public MultiResponse getTeachCycle() {
        List<Map<String, String>> mapList = new ArrayList<>();
        QueryTeacherCycleReq query = new QueryTeacherCycleReq();
        query.setPageSize(10000);
        query.setPartyId(getPartyId());
        IPage<TeacherCycleResp> page = teacherCycleService.queryList(query);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            for (TeacherCycleResp v : page.getRecords()) {
                Map<String, String> map = new HashMap<>();
                map.put("key", v.getId().toString());
                String name=v.getCycleName() + (v.getSemester().equals("1") ? "上学期":"下学期");
                map.put("name", name);
                mapList.add(map);
            }
        }
        return MultiResponse.ofWithoutTotal(mapList);
    }

    @ApiOperation(value = "获取体测周期", notes = "获取体测周期")
    @PostMapping("/testCycle")
    public MultiResponse getTestCycle(@RequestBody QuerySchoolTestCycleReq req) {
        List<Map<String, String>> mapList = new ArrayList<>();
        XunFeiCommonApiService xunFeiApiService = new XunFeiCommonApiService();
        QueryTestCycleReq queryTestCycleReq = new QueryTestCycleReq();
        queryTestCycleReq.setTeachCycleId(req.getTeachCycleId());
        queryTestCycleReq.setType(req.getType());
        ApiListResponse<TestCycleResp> response = xunFeiApiService.getTestCycle(queryTestCycleReq, getPartyId().toString(), null, getUserId().toString());
        if (response.getMsg().equals("success")) {
            for (TestCycleResp v : response.getData()) {
                Map<String, String> map = new HashMap<>();
                map.put("key", v.getId().toString());
                map.put("name", v.getCycleName());
                mapList.add(map);
            }
        }
        return MultiResponse.ofWithoutTotal(mapList);
    }

    @ApiOperation(value = "获取已经存在校区下 班级类型，学段，年级，班级列表 ", notes = "获取校区下 班级类型，学段，年级，班级列表")
    @PostMapping("/class")
    public MultiResponse getClassInfo(@RequestBody QueryClassesInfoReq request) {
        List<Map<String, String>> mapList = new ArrayList<>();
        request.setPageSize(10000);
        request.setPartyId(getPartyId());
        IPage<ClassesInfoResp> page = classesInfoService.queryList(request);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            if (request.getResultType().equals(1)) {
                mapList = page.getRecords().stream().map(s -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("key", s.getType().toString());
                    map.put("name", s.getTypeName());
                    return map;
                }).distinct().sorted(Comparator.comparing(s->s.get("key"))).collect(Collectors.toList());
            } else if (request.getResultType().equals(2)) {
                mapList = page.getRecords().stream().map(s -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("key", s.getSection().toString());
                    map.put("name", s.getSectionName());
                    return map;
                }).distinct().collect(Collectors.toList());
            } else if (request.getResultType().equals(3)) {
                mapList = page.getRecords().stream().map(s -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("key", s.getGrade().toString());
                    map.put("name", s.getGradeName());
                    return map;
                }).distinct().sorted(Comparator.comparing(s->s.get("key"))).collect(Collectors.toList());
            } else {
                mapList = page.getRecords().stream().map(s -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("key", s.getClassId().toString());
                    map.put("name", s.getClassName());
                    return map;
                }).distinct().sorted(Comparator.comparing(s->s.get("key"))).collect(Collectors.toList());
            }
        }
        return MultiResponse.ofWithoutTotal(mapList);
    }


    @ApiOperation(value = "获取学段下的年级", notes = "获取学段下的年级")
    @RequestMapping(value="/sectionClass",method={RequestMethod.GET,RequestMethod.POST})
    public MultiResponse<KeyValueResp> getSectionClassInfo(@RequestBody(required = false) QueryClassesInfoReq request) {
        List<KeyValueResp> list = new ArrayList<>();
        if(null == request){
            request =new  QueryClassesInfoReq();
        }
        request.setPartyId(getPartyId());
        request.setPageSize(10000);
        IPage<ClassesInfoResp> page = classesInfoService.queryList(request);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            KeyValueResp a = null;
            KeyValueResp b = null;
            KeyValueResp c = null;
            KeyValueResp d = null;
            Set<Integer> gradeSet = new HashSet<>();
            for (ClassesInfoResp classesInfoResp : page.getRecords()) {
                if (classesInfoResp.getType().equals(1)) {
                    if(null == d){
                        d = new KeyValueResp();
                    }
                    d.setValue(classesInfoResp.getType().toString());
                    d.setLabel(ClassesTypeEnum.layered_classes.getRemark());
                    if (CollectionUtil.isEmpty(d.getList())) {
                        d.setList(new ArrayList<KeyValueResp>());
                    }
                    d.setLabel("分层班");
                    d.setValue("");
                    d.getList().add(new KeyValueResp(classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                } else {
                    if (classesInfoResp.getSection().equals(SectionEnum.PRIMARY_SCHOOL.getType())) {
                        if(null == a){
                            a = new KeyValueResp();
                        }
                        a.setValue(SectionEnum.PRIMARY_SCHOOL.getType().toString());
                        a.setLabel(SectionEnum.PRIMARY_SCHOOL.getRemark());
                        if (CollectionUtil.isEmpty(a.getList())) {
                            a.setList(new ArrayList<KeyValueResp>());
                        }
                        if (!gradeSet.contains(classesInfoResp.getGrade())) {
                            a.getList().add(new KeyValueResp(GradeEnum.getGradeEnum(classesInfoResp.getGrade()), classesInfoResp.getGrade().toString(),classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                            gradeSet.add(classesInfoResp.getGrade());
                        }else{
                            for(KeyValueResp keyValueResp :a.getList()){
                                 if(keyValueResp.getValue().equals(classesInfoResp.getGrade().toString())){
                                     keyValueResp.getList().add(new KeyValueResp(classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                                     break;
                                 }
                            }
                        }
                    } else if (classesInfoResp.getSection().equals(SectionEnum.JUNIOR_HIGH_SCHOOL.getType())) {
                        if(null == b){
                            b = new KeyValueResp();
                        }
                        b.setValue(SectionEnum.JUNIOR_HIGH_SCHOOL.getType().toString());
                        b.setLabel(SectionEnum.JUNIOR_HIGH_SCHOOL.getRemark());
                        if (CollectionUtil.isEmpty(b.getList())) {
                            b.setList(new ArrayList<KeyValueResp>());
                        }
                        if (!gradeSet.contains(classesInfoResp.getGrade())) {
                            b.getList().add(new KeyValueResp(GradeEnum.getGradeEnum(classesInfoResp.getGrade()), classesInfoResp.getGrade().toString(),classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                            gradeSet.add(classesInfoResp.getGrade());
                        }else{
                            for(KeyValueResp keyValueResp :b.getList()){
                                if(keyValueResp.getValue().equals(classesInfoResp.getGrade().toString())){
                                    keyValueResp.getList().add(new KeyValueResp(classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                                    break;
                                }
                            }
                        }
                    } else if (classesInfoResp.getSection().equals(SectionEnum.HIGH_SCHOOL.getType())) {
                        if(null == c){
                            c = new KeyValueResp();
                        }
                        c.setValue(SectionEnum.HIGH_SCHOOL.getType().toString());
                        c.setLabel(SectionEnum.HIGH_SCHOOL.getRemark());
                        if (CollectionUtil.isEmpty(c.getList())) {
                            c.setList(new ArrayList<KeyValueResp>());
                        }
                        if (!gradeSet.contains(classesInfoResp.getGrade())) {
                            c.getList().add(new KeyValueResp(GradeEnum.getGradeEnum(classesInfoResp.getGrade()), classesInfoResp.getGrade().toString(),classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                            gradeSet.add(classesInfoResp.getGrade());
                        }else{
                            for(KeyValueResp keyValueResp :c.getList()){
                                if(keyValueResp.getValue().equals(classesInfoResp.getGrade().toString())){
                                    keyValueResp.getList().add(new KeyValueResp(classesInfoResp.getClassName(),classesInfoResp.getClassId().toString()));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (null != a) {
                a.getList().sort(Comparator.comparing(KeyValueResp ::getValue));
                list.add(a);
            }
            if (null != b) {
                b.getList().sort(Comparator.comparing(KeyValueResp ::getValue));
                list.add(b);
            }
            if (null != c) {
                c.getList().sort(Comparator.comparing(KeyValueResp ::getValue));
                list.add(c);
            }
            if (null != d) {
                d.getList().sort(Comparator.comparing(KeyValueResp ::getValue));
                list.add(d);
            }
        }
        return MultiResponse.ofWithoutTotal(list);
    }

}
